package com.example.taphelper

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.taphelper.service.TapAccessibilityService
import com.example.taphelper.service.TapForegroundService
import com.example.taphelper.utils.ClickHistoryManager
import com.example.taphelper.utils.PermissionUtils
import com.example.taphelper.utils.TapConfig

class MainActivity : AppCompatActivity() {
    
    companion object {
        private const val TAG = "MainActivity"
        private const val PREFS_NAME = "tap_helper_prefs"
        private const val KEY_X = "click_x"
        private const val KEY_Y = "click_y"
        private const val KEY_INTERVAL = "click_interval"
        private const val KEY_DELAY = "click_delay"
        private const val REQUEST_CODE_FULLSCREEN = 1001
    }
    
    // 视图组件
    private lateinit var tvAccessibilityStatus: TextView
    private lateinit var tvOverlayStatus: TextView
    private lateinit var tvBatteryStatus: TextView
    private lateinit var tvStatus: TextView
    
    private lateinit var btnEnableAccessibility: Button
    private lateinit var btnEnableOverlay: Button
    private lateinit var btnDisableBatteryOptimization: Button
    
    private lateinit var etXCoordinate: EditText
    private lateinit var etYCoordinate: EditText
    private lateinit var etInterval: EditText
    
    private lateinit var btnTestClick: Button
    private lateinit var btnStartClicking: Button
    private lateinit var btnStopClicking: Button
    private lateinit var btnStartService: Button
    private lateinit var btnStopService: Button
    
    // 数据
    private lateinit var sharedPrefs: SharedPreferences
    private var handler = Handler(Looper.getMainLooper())
    private var statusUpdateRunnable: Runnable? = null
    private lateinit var historyManager: ClickHistoryManager
    
    // 权限请求器
    private val notificationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            Log.d(TAG, "通知权限已获取")
        } else {
            Log.w(TAG, "通知权限被拒绝")
        }
    }
    
    // 图片选择启动器
    private val selectImageLauncher = registerForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            openFullScreenImage(it)
        }
    }
    
    // 全屏图片Activity结果处理
    private val fullScreenActivityLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK && result.data != null) {
            val clickPosition = result.data?.getStringExtra(FullScreenImageActivity.RESULT_CLICK_POSITION)
            val spaceTime = result.data?.getFloatExtra(FullScreenImageActivity.RESULT_SPACE_TIME, 0f)
            val delayTime = result.data?.getFloatExtra(FullScreenImageActivity.RESULT_DELAY_TIME, 0f)
            
            Log.d(TAG, "全屏选择结果: 位置=$clickPosition, 间隔=${spaceTime}秒, 延迟=${delayTime}秒")
            Toast.makeText(this, "自动点击已启动: $clickPosition", Toast.LENGTH_LONG).show()
        }
    }
    
    // 存储权限请求器
    private val storagePermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val granted = permissions.values.all { it }
        if (granted) {
            openImagePicker()
        } else {
            Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        initViews()
        initData()
        setupListeners()
        requestNotificationPermission()
        startStatusUpdate()
        
        // 启动前台服务
        TapForegroundService.startService(this)
    }
    
    override fun onResume() {
        super.onResume()
        updatePermissionStatus()
        updateServiceStatus()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        stopStatusUpdate()
    }
    
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_history -> {
                showClickHistoryDialog()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    private fun initViews() {
        // 状态显示
        tvAccessibilityStatus = findViewById(R.id.tvAccessibilityStatus)
        tvOverlayStatus = findViewById(R.id.tvOverlayStatus)
        tvBatteryStatus = findViewById(R.id.tvBatteryStatus)
        tvStatus = findViewById(R.id.tvStatus)
        
        // 权限按钮
        btnEnableAccessibility = findViewById(R.id.btnEnableAccessibility)
        btnEnableOverlay = findViewById(R.id.btnEnableOverlay)
        btnDisableBatteryOptimization = findViewById(R.id.btnDisableBatteryOptimization)
        
        // 输入框
        etXCoordinate = findViewById(R.id.etXCoordinate)
        etYCoordinate = findViewById(R.id.etYCoordinate)
        etInterval = findViewById(R.id.etInterval)
        
        // 功能按钮
        btnTestClick = findViewById(R.id.btnTestClick)
        btnStartClicking = findViewById(R.id.btnStartClicking)
        btnStopClicking = findViewById(R.id.btnStopClicking)
        btnStartService = findViewById(R.id.btnStartService)
        btnStopService = findViewById(R.id.btnStopService)
        // btnSelectImage按钮暂时不需要，将图片选择功能集成到btnStartClicking中
    }
    
    private fun initData() {
        sharedPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        historyManager = ClickHistoryManager(this)
        loadSavedConfig()
    }
    
    private fun setupListeners() {
        // 权限按钮
        btnEnableAccessibility.setOnClickListener {
            PermissionUtils.openAccessibilitySettings(this)
        }
        
        btnEnableOverlay.setOnClickListener {
            PermissionUtils.requestOverlayPermission(this)
        }
        
        btnDisableBatteryOptimization.setOnClickListener {
            PermissionUtils.requestIgnoreBatteryOptimizations(this)
        }
        
        // 功能按钮
        btnTestClick.setOnClickListener {
            performTestClick()
        }
        
        // 修改开始点击按钮的功能 - 现在启动图片选择流程
        btnStartClicking.setOnClickListener {
            startImageSelectionFlow()
        }
        
        btnStopClicking.setOnClickListener {
            stopAutoClicking()
        }
        
        btnStartService.setOnClickListener {
            TapForegroundService.startService(this)
            Toast.makeText(this, "前台服务已启动", Toast.LENGTH_SHORT).show()
        }
        
        btnStopService.setOnClickListener {
            TapForegroundService.stopService(this)
            Toast.makeText(this, "前台服务已停止", Toast.LENGTH_SHORT).show()
        }
        
        // 图片选择功能已集成到btnStartClicking中
    }
    
    private fun loadSavedConfig() {
        val x = sharedPrefs.getInt(KEY_X, 540)
        val y = sharedPrefs.getInt(KEY_Y, 960)
        val interval = sharedPrefs.getFloat(KEY_INTERVAL, 1.0f)
        
        etXCoordinate.setText(x.toString())
        etYCoordinate.setText(y.toString())
        etInterval.setText(interval.toString())
    }
    
    private fun saveConfig() {
        val x = etXCoordinate.text.toString().toIntOrNull() ?: 540
        val y = etYCoordinate.text.toString().toIntOrNull() ?: 960
        val interval = etInterval.text.toString().toFloatOrNull() ?: 1.0f
        
        sharedPrefs.edit()
            .putInt(KEY_X, x)
            .putInt(KEY_Y, y)
            .putFloat(KEY_INTERVAL, interval)
            .apply()
    }
    
    private fun getCurrentConfig(): TapConfig? {
        val x = etXCoordinate.text.toString().toIntOrNull()
        val y = etYCoordinate.text.toString().toIntOrNull()
        val interval = etInterval.text.toString().toFloatOrNull()
        
        if (x == null || y == null || interval == null) {
            Toast.makeText(this, "请检查输入参数", Toast.LENGTH_SHORT).show()
            return null
        }
        
        if (x <= 0 || y <= 0 || interval <= 0) {
            Toast.makeText(this, "参数必须大于0", Toast.LENGTH_SHORT).show()
            return null
        }
        
        return TapConfig(x, y, (interval * 1000).toLong(), 3000, true)
    }
    
    private fun performTestClick() {
        val config = getCurrentConfig() ?: return
        
        val service = TapAccessibilityService.instance
        if (service == null) {
            Toast.makeText(this, "请先启用无障碍服务", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 创建测试配置，只点击一次
        val testConfig = TapConfig().apply {
            x = config.x
            y = config.y
            setIntervalSeconds(1.0f)
            setDelaySeconds(0f)
            isEnabled = true
            // 关闭随机化，进行精确测试
            randomOffsetRange = 0.0f
            intervalRandomRange = 0.0f
            enableRandomPause = false
        }
        
        service.startClickingWithDelay(testConfig)
        
        // 1秒后停止测试点击
        Handler(Looper.getMainLooper()).postDelayed({
            service.stopClicking()
        }, 1100)
        
        Toast.makeText(this, "测试点击已执行: (${config.x}, ${config.y})", Toast.LENGTH_SHORT).show()
        saveConfig()
    }
    
    /**
     * 启动图片选择流程
     */
    private fun startImageSelectionFlow() {
        if (!checkPermissions()) return
        
        // 检查存储权限
        if (checkStoragePermissions()) {
            openImagePicker()
        } else {
            requestStoragePermissions()
        }
    }
    
    /**
     * 检查存储权限
     */
    private fun checkStoragePermissions(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * 请求存储权限
     */
    private fun requestStoragePermissions() {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        
        storagePermissionLauncher.launch(permissions)
    }
    
    /**
     * 打开图片选择器
     */
    private fun openImagePicker() {
        try {
            selectImageLauncher.launch("image/*")
        } catch (e: Exception) {
            Log.e(TAG, "打开图片选择器失败", e)
            Toast.makeText(this, "无法打开图片选择器", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 打开全屏图片显示界面
     */
    private fun openFullScreenImage(imageUri: Uri) {
        val intent = Intent(this, FullScreenImageActivity::class.java)
        intent.putExtra(FullScreenImageActivity.EXTRA_IMAGE_URI, imageUri.toString())
        fullScreenActivityLauncher.launch(intent)
    }
    
    private fun stopAutoClicking() {
        val service = TapAccessibilityService.instance
        service?.stopClicking()
        Toast.makeText(this, "停止自动点击", Toast.LENGTH_SHORT).show()
    }
    
    private fun checkPermissions(): Boolean {
        if (!PermissionUtils.isAccessibilityServiceEnabled(this)) {
            Toast.makeText(this, "请先启用无障碍服务", Toast.LENGTH_SHORT).show()
            return false
        }
        
        return true
    }
    
    private fun updatePermissionStatus() {
        // 无障碍服务状态
        val accessibilityEnabled = PermissionUtils.isAccessibilityServiceEnabled(this)
        tvAccessibilityStatus.text = if (accessibilityEnabled) {
            "无障碍服务: 已启用"
        } else {
            "无障碍服务: 未启用"
        }
        tvAccessibilityStatus.setTextColor(
            ContextCompat.getColor(
                this,
                if (accessibilityEnabled) android.R.color.holo_green_dark else android.R.color.holo_red_dark
            )
        )
        
        // 悬浮窗权限状态
        val overlayEnabled = PermissionUtils.canDrawOverlays(this)
        tvOverlayStatus.text = if (overlayEnabled) {
            "悬浮窗权限: 已启用"
        } else {
            "悬浮窗权限: 未启用"
        }
        tvOverlayStatus.setTextColor(
            ContextCompat.getColor(
                this,
                if (overlayEnabled) android.R.color.holo_green_dark else android.R.color.holo_red_dark
            )
        )
        
        // 电池优化状态
        val batteryOptimized = PermissionUtils.isIgnoringBatteryOptimizations(this)
        tvBatteryStatus.text = if (batteryOptimized) {
            "电池优化: 已关闭"
        } else {
            "电池优化: 未关闭"
        }
        tvBatteryStatus.setTextColor(
            ContextCompat.getColor(
                this,
                if (batteryOptimized) android.R.color.holo_green_dark else android.R.color.holo_orange_dark
            )
        )
    }
    
    private fun updateServiceStatus() {
        val service = TapAccessibilityService.instance
        val isClicking = service?.isCurrentlyClicking() ?: false
        
        tvStatus.text = if (service != null) {
            if (isClicking) {
                val config = service.getCurrentConfig()
                val count = service.getClickCount()
                if (config?.useRectangleMode == true) {
                    "🔲 矩形区域点击中 (已点击 $count 次)\n" +
                    "区域: (${config.rectLeft},${config.rectTop}) 到 (${config.rectRight},${config.rectBottom})\n" +
                    "间隔: ${config.intervalMillis}ms ±${config.intervalRandomRange}ms"
                } else {
                    "📍 单点智能点击中 (已点击 $count 次)\n" +
                    "目标: (${config?.x}, ${config?.y}) ±${config?.randomOffsetRange}px\n" +
                    "间隔: ${config?.intervalMillis}ms ±${config?.intervalRandomRange}ms"
                }
            } else {
                getString(R.string.service_stopped)
            }
        } else {
            "服务未连接"
        }
        
        tvStatus.setTextColor(
            ContextCompat.getColor(
                this,
                if (service != null && isClicking) {
                    android.R.color.holo_green_dark
                } else {
                    android.R.color.holo_red_dark
                }
            )
        )
    }
    
    private fun startStatusUpdate() {
        statusUpdateRunnable = object : Runnable {
            override fun run() {
                updateServiceStatus()
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(statusUpdateRunnable!!)
    }
    
    private fun stopStatusUpdate() {
        statusUpdateRunnable?.let { handler.removeCallbacks(it) }
        statusUpdateRunnable = null
    }
    
    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
    
    /**
     * 显示点击历史记录对话框
     */
    private fun showClickHistoryDialog() {
        // 创建包含统计信息和历史记录的文本
        val historyText = "${historyManager.getStatistics()}\n\n${historyManager.getFormattedHistory()}"
        
        val scrollView = ScrollView(this)
        val textView = TextView(this).apply {
            text = historyText
            textSize = 12f
            setPadding(32, 32, 32, 32)
            setTextIsSelectable(true)
        }
        scrollView.addView(textView)
        
        AlertDialog.Builder(this)
            .setTitle("📖 点击历史记录")
            .setView(scrollView as android.view.View)
            .setPositiveButton("关闭") { dialog, _ -> dialog.dismiss() }
            .setNeutralButton("清空历史") { _, _ ->
                showClearHistoryConfirmDialog()
            }
            .setNegativeButton("导出") { _, _ ->
                exportHistory()
            }
            .show()
    }
    
    /**
     * 显示清空历史记录确认对话框
     */
    private fun showClearHistoryConfirmDialog() {
        AlertDialog.Builder(this)
            .setTitle("⚠️ 确认清空")
            .setMessage("确定要清空所有点击历史记录吗？此操作不可撤销。")
            .setPositiveButton("确定") { _, _ ->
                historyManager.clearHistory()
                Toast.makeText(this, "历史记录已清空", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
            .show()
    }
    
    /**
     * 导出历史记录
     */
    private fun exportHistory() {
        val historyText = "${historyManager.getStatistics()}\n\n${historyManager.getFormattedHistory()}"
        
        val shareIntent = Intent().apply {
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_TEXT, historyText)
            putExtra(Intent.EXTRA_SUBJECT, "点击助手 - 历史记录")
            type = "text/plain"
        }
        
        try {
            startActivity(Intent.createChooser(shareIntent, "导出历史记录"))
        } catch (e: Exception) {
            Toast.makeText(this, "导出失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
} 